package com.ldc.commonres.common

import android.annotation.SuppressLint
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.recyclerview.widget.RecyclerView

abstract class BaseRvAdapter<T>(@LayoutRes layoutId: Int) :
    RecyclerView.Adapter<BaseRvViewHolder>() {
    @LayoutRes
    private var layoutId: Int? = layoutId

    // 数据
    private var mData: MutableList<T> = mutableListOf()

    // 获取数据
    fun getData(): MutableList<T> = mData

    //是否为空数据
    fun isEmptyData(): Boolean = mData.isEmpty()

    @SuppressLint("NotifyDataSetChanged")
    fun newData(data: List<T>?) {
        if (data.isNullOrEmpty()) {
            mData.clear()
        } else {
            mData = ArrayList(data)
        }
        notifyDataSetChanged()

    }

    @SuppressLint("NotifyDataSetChanged")
    fun addNewData(data: List<T>?) {
        if (data.isNullOrEmpty()) return
        mData.addAll(data)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseRvViewHolder {
        return BaseRvViewHolder.createViewHolder(parent, viewType, layoutId!!)
    }

    override fun onBindViewHolder(holder: BaseRvViewHolder, position: Int) {
        if (mData.isNotEmpty()) {
            val data = mData[position]
            convertTo(holder, data, position)
        }
    }

    abstract fun convertTo(holder: BaseRvViewHolder, data: T, position: Int)

    override fun getItemCount(): Int {
        return mData.size
    }


}